from flask import jsonify, request
from services.auth_service import AuthService

class AuthController:
    """认证控制器类 - 表现层"""
    
    def __init__(self):
        self.auth_service = AuthService()
    
    def login(self):
        """处理登录请求"""
        try:
            data = request.get_json()
            username = data.get('username', '').strip()
            password = data.get('password', '').strip()
            
            # 调用业务逻辑层处理登录
            result = self.auth_service.login(username, password)
            
            return jsonify({
                'success': result['success'],
                'message': result['message'],
                'token': result.get('token'),
                'user': result.get('user')
            }), result['status_code']
            
        except Exception as e:
            print(f"登录控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '登录失败，服务器错误'
            }), 500
    
    def verify_token(self):
        """验证token有效性"""
        try:
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            user = self.auth_service.get_user_by_token(token)
            if not user:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            return jsonify({
                'success': True,
                'message': 'token验证成功',
                'user': {
                    'id': user['id'],
                    'username': user['username'],
                    'nickname': user['nickname'],
                    'phone': user['phone'],
                    'email': user['email'],
                    'driving_years': user['driving_years'],
                    'city': user['city'],
                    'birthday': user['birthday'].strftime('%Y-%m-%d') if user['birthday'] else None,
                    'bio': user['bio'],
                    'created_at': user['created_at'].strftime('%Y-%m-%d %H:%M:%S')
                }
            }), 200
            
        except Exception as e:
            print(f"token验证错误: {e}")
            return jsonify({
                'success': False,
                'message': 'token验证失败'
            }), 500
    
    def register(self):
        """处理注册请求"""
        try:
            data = request.get_json()
            username = data.get('username', '').strip()
            password = data.get('password', '').strip()
            confirm_password = data.get('confirmPassword', '').strip()
            
            # 调用业务逻辑层处理注册
            result = self.auth_service.register(username, password, confirm_password)
            
            return jsonify({
                'success': result['success'],
                'message': result['message'],
                'token': result.get('token'),
                'user': result.get('user')
            }), result['status_code']
            
        except Exception as e:
            print(f"注册控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '注册失败，服务器错误'
            }), 500